<template>
  <div class="timeline-tab">
    <el-row :gutter="24" class="timeline-row">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Clock /></el-icon>
              <span>小时分布</span>
            </div>
          </template>
          
          <div ref="hourlyChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Calendar /></el-icon>
              <span>日期分布</span>
            </div>
          </template>
          
          <div ref="dailyChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="24" class="timeline-row">
      <el-col :xs="24" :lg="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><TrendCharts /></el-icon>
              <span>子系统错误时间分布</span>
            </div>
          </template>
          
          <div ref="criticalTimeNodesChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useAnalysisStore } from '@/stores/analysis'
import * as echarts from 'echarts'
import { Clock, Calendar, TrendCharts } from '@element-plus/icons-vue'

// Store
const analysisStore = useAnalysisStore()

// 图表引用
const hourlyChartRef = ref<HTMLElement>()
const dailyChartRef = ref<HTMLElement>()
const criticalTimeNodesChartRef = ref<HTMLElement>() // 新增关键时间节点图表引用
let hourlyChart: echarts.ECharts | null = null
let dailyChart: echarts.ECharts | null = null
let criticalTimeNodesChart: echarts.ECharts | null = null // 新增关键时间节点图表实例

// 计算属性
const timePatterns = computed(() => {
  const fixedLogs = analysisStore.analysisData?.reboot_analysis?.fixed_logs || []
  
  const hourlyDistribution = new Array(24).fill(0)
  const dailyDistribution: { [key: string]: number } = {}
  const levelDistribution: { [key: string]: number } = {}

  fixedLogs.forEach((log: any) => {
    try {
      const logDt = new Date(log.datetime)
      // 小时分布
      hourlyDistribution[logDt.getHours()] += 1
      // 日期分布
      const dateKey = logDt.toISOString().slice(0, 10)
      dailyDistribution[dateKey] = (dailyDistribution[dateKey] || 0) + 1
      // 级别分布
      levelDistribution[log.level] = (levelDistribution[log.level] || 0) + 1
    } catch (e) {
      console.error("Error parsing log datetime:", log.datetime, e)
    }
  })

  return {
    hourly_distribution: hourlyDistribution,
    daily_distribution: dailyDistribution,
    level_distribution: levelDistribution,
  }
})

const criticalTimeNodes = computed(() => {
  return analysisStore.analysisData?.critical_time_nodes || { timestamps: [], series: {} }
})

// 初始化小时分布图表
const initHourlyChart = () => {
  if (!hourlyChartRef.value) return
  
  hourlyChart = echarts.init(hourlyChartRef.value)
  
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%', // 为dataZoom留出空间
      containLabel: true
    },
    xAxis: {
      type: 'time', // 改为时间轴
      name: '真实时间',
      axisLabel: {
        formatter: (value: string) => {
          return new Date(value).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '总错误数量' // 更改为总错误数量
    },
    series: [
      {
        name: '总错误数量',
        type: 'line',
        smooth: true,
        showSymbol: false, // 隐藏时间点圆圈
        data: [],
        itemStyle: {
          color: '#409eff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100,
        height: 30,
        bottom: 0
      }
    ]
  }
  
  hourlyChart.setOption(option)
}

// 更新小时分布图表
const updateHourlyChart = () => {
  if (!hourlyChart) return

  const fixedLogs = analysisStore.analysisData?.reboot_analysis?.fixed_logs || []
  const rebootEvents = analysisStore.analysisData?.reboot_analysis?.reboot_events || []
  const errorLogs = fixedLogs.filter((log: any) => log.level.toUpperCase() === 'ERROR')

  // 按照小时间隔聚合错误事件
  const timeGroupedErrors: { [key: string]: number } = {}
  errorLogs.forEach((log: any) => {
    try {
      const logDt = new Date(log.datetime)
      // 将时间向下取整到最近的小时
      const aggregatedDt = new Date(logDt.getFullYear(), logDt.getMonth(), logDt.getDate(), logDt.getHours(), 0, 0, 0)
      const timestampKey = aggregatedDt.toISOString()
      timeGroupedErrors[timestampKey] = (timeGroupedErrors[timestampKey] || 0) + 1
    } catch (e) {
      console.error("Error processing log datetime for hourly chart:", log.datetime, e)
    }
  })

  const sortedTimestamps = Object.keys(timeGroupedErrors).sort()
  const chartData = sortedTimestamps.map(ts => [new Date(ts), timeGroupedErrors[ts]])

  // 为重启事件生成markArea
  const markAreas: echarts.SeriesMarkAreaOption['data'] = []
  const colors = ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)'] // 预定义颜色，可以根据需要扩展
  let colorIndex = 0
  let runSegmentIndex = 1; // 用于生成“运行 N”的计数器

  if (rebootEvents.length > 0) {
    // 处理第一个重启事件之前的区域
    const firstLogTime = chartData.length > 0 ? chartData[0][0] : null;
    const firstRebootStart = new Date(rebootEvents[0].reboot_start_log_time);
    if (firstLogTime && firstRebootStart > firstLogTime) {
      markAreas.push([{
        name: `运行 ${runSegmentIndex++}`,
        xAxis: firstLogTime.toISOString(),
        itemStyle: { color: colors[colorIndex % colors.length] }
      }, {
        xAxis: firstRebootStart.toISOString()
      }]);
      colorIndex++;
    }

    // 处理重启事件之间的区域
    for (let i = 0; i < rebootEvents.length; i++) {
      const reboot = rebootEvents[i];
      const startDateTime = new Date(reboot.reboot_start_log_time);
      const endDateTime = new Date(reboot.reboot_end_log_time);

      // 添加重启区间 (现在也叫运行)
      markAreas.push([{
        name: `运行 ${runSegmentIndex++}`,
        xAxis: startDateTime.toISOString(),
        itemStyle: { color: colors[colorIndex % colors.length] }
      }, {
        xAxis: endDateTime.toISOString()
      }]);
      colorIndex++;

      // 如果不是最后一个重启事件，添加下一个重启事件之前的正常运行区间
      if (i < rebootEvents.length - 1) {
        const nextRebootStart = new Date(rebootEvents[i + 1].reboot_start_log_time);
        if (nextRebootStart > endDateTime) {
          markAreas.push([{
            name: `运行 ${runSegmentIndex++}`,
            xAxis: endDateTime.toISOString(),
            itemStyle: { color: colors[colorIndex % colors.length] } // 可以用不同的颜色区分正常运行和重启
          }, {
            xAxis: nextRebootStart.toISOString()
          }]);
          colorIndex++;
        }
      }
    }

    // 处理最后一个重启事件之后的区域
    const lastLogTime = chartData.length > 0 ? chartData[chartData.length - 1][0] : null;
    const lastRebootEnd = new Date(rebootEvents[rebootEvents.length - 1].reboot_end_log_time);
    if (lastLogTime && lastRebootEnd < lastLogTime) {
      markAreas.push([{
        name: `运行 ${runSegmentIndex++}`,
        xAxis: lastRebootEnd.toISOString(),
        itemStyle: { color: colors[colorIndex % colors.length] }
      }, {
        xAxis: lastLogTime.toISOString()
      }]);
      colorIndex++;
    }

  }

  hourlyChart.setOption({
    xAxis: {
      type: 'time'
    },
    series: [{
      name: '总错误数量',
      data: chartData,
      markArea: {
        data: markAreas
      }
    }]
  })
}

// 初始化日期分布图表
const initDailyChart = () => {
  if (!dailyChartRef.value) return
  
  dailyChart = echarts.init(dailyChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      name: '日期',
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '日志数量'
    },
    series: [
      {
        name: '日志数量',
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#67c23a'
        }
      }
    ]
  }
  
  dailyChart.setOption(option)
}

// 更新日期分布图表
const updateDailyChart = () => {
  if (!dailyChart || !timePatterns.value.daily_distribution) return
  
  const sortedDates = Object.keys(timePatterns.value.daily_distribution).sort()
  const data = sortedDates.map(date => timePatterns.value.daily_distribution[date])
  
  dailyChart.setOption({
    xAxis: {
      data: sortedDates
    },
    series: [{
      data
    }]
  })
}

// 初始化关键时间节点图表
const initCriticalTimeNodesChart = () => {
  if (!criticalTimeNodesChartRef.value) return

  criticalTimeNodesChart = echarts.init(criticalTimeNodesChartRef.value)

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: [] as string[], // 动态添加组件名称
      bottom: 5,
      type: 'scroll',
      orient: 'horizontal',
      padding: [0, 0, 0, 0]
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'time',
      name: '真实时间',
      axisLabel: {
        formatter: (value: string) => {
          return new Date(value).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '错误事件数量',
      minInterval: 1 // 确保Y轴刻度是整数
    },
    series: [], // 动态添加系列
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100,
        height: 30,
        bottom: 0
      }
    ]
  }

  criticalTimeNodesChart.setOption(option)
}

// 更新关键时间节点图表
const updateCriticalTimeNodesChart = () => {
  if (!criticalTimeNodesChart || !criticalTimeNodes.value.timestamps.length) return

  const series: echarts.SeriesOption[] = []
  const legendData: string[] = []

  for (const component in criticalTimeNodes.value.series) {
    legendData.push(component)
    const data = criticalTimeNodes.value.series[component].map((count: number, index: number) => [
      criticalTimeNodes.value.timestamps[index],
      count
    ])
    series.push({
      name: component,
      type: 'line',
      smooth: true,
      showSymbol: false, // 隐藏时间点圆圈
      stack: 'total', // 堆叠显示
      emphasis: {
        focus: 'series'
      },
      areaStyle: {},
      data: data
    })
  }

  criticalTimeNodesChart.setOption({
    legend: {
      data: legendData
    },
    xAxis: { // 移除 data 属性，因为 type 已经是 'time'
      // data: criticalTimeNodes.value.timestamps 
    },
    series: series
  })
}

// 监听数据变化
watch(timePatterns, () => {
  updateHourlyChart()
  updateDailyChart()
  updateCriticalTimeNodesChart() // 新增：更新关键时间节点图表
}, { deep: true })

// 组件挂载
onMounted(() => {
  initHourlyChart()
  initDailyChart()
  initCriticalTimeNodesChart() // 新增：初始化关键时间节点图表
  updateHourlyChart()
  updateDailyChart()
  updateCriticalTimeNodesChart() // 新增：首次加载时更新关键时间节点图表
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    hourlyChart?.resize()
    dailyChart?.resize()
    criticalTimeNodesChart?.resize() // 新增：重置关键时间节点图表大小
  })
})
</script>

<style scoped>
.timeline-tab {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.timeline-row {
  flex: 1;
  height: 100%;
}

.timeline-row :deep(.el-col) {
  height: 100%;
}

.chart-card {
  height: 100%;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  flex-shrink: 0;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .timeline-row {
    flex-direction: column;
  }
  
  .timeline-row :deep(.el-col) {
    height: auto;
    margin-bottom: 16px;
  }
  
  .chart-card {
    height: 400px;
  }
  
  .chart-container {
    min-height: 250px;
  }
}

@media (max-width: 480px) {
  .timeline-tab {
    padding: 0;
  }
  
  .chart-container {
    min-height: 200px;
  }
}
</style> 